<?php

class Backend extends MY_Controller {

	public function __construct() {
		parent::__construct();

		$this->initialize();
	}

	private function initialize() {

		$this->check_login();

		//$this->check_permission();

		$lang = $this->input->cookie('lang');

		$lang = empty($lang) ? 'zh' : $lang;

		$this->set_data(array('g_lang' => $lang));

		$this->lang->load('ui', $lang == 'en' ? 'english' : 'chinese');

		$this->set_title($lang == 'en' ? 'English Title' : '中文标题');

		$this->set_layout('backend/layout');

		$this->set_js('LANG', "'{$lang}'");
		$this->set_js('SITE_URL', '\'' . SITE_URL . '\'');

		$this->load_js(array('jquery.min', 'jquery.tmpl.min', 'lib', 'backend'));

		$this->load_css(array('global', 'lib', 'backend'));
	}

	private function check_login() {
		$user_id = intval($this->session->userdata('g_user_id'));

		if ($user_id <= 0) {
			if ($this->input->is_ajax_request()) {
				$this->json_back('XT004', '请先登录');
			} else {
				$this->load->helper('url');
				redirect('/backend/auth/login_error');
			}
		}
	}

	private function check_permission() {
		$user_id = intval($this->session->userdata('g_user_id'));

		$controller = trim($this->uri->segment(1, 'home'));
		$action = trim($this->uri->segment(2, 'index'));

		$path = "/{$controller}/{$action}";

		$this->load->model(array('user_model', 'permission_group_model'));

		$user = $this->user_model->find($user_id);
		$user_permission_group = $this->permission_group_model->find($user->permission_group);


		$allow_paths = array(
			'/common/index',
			'/common/header',
			'/common/navigation',
			'/home/index'
		);

		if ($user_id != 1 && !in_array($path, array_merge($allow_paths, explode(',', $user_permission_group->path)))) {
			if ($this->input->is_ajax_request()) {
				$this->json_back('XT003', '请的帐号不具备此操作权限');
			} else {
				$this->load->helper('url');
				redirect('/auth/permission_error');
			}
		}
	}

	public function language() {
		//通过get参数来设置语言
		$lang = $this->input->get('lang');
		if ($lang) {
			$this->input->set_cookie(array(
				'name' => 'lang',
				'value' => $lang,
				'expire' => '86500'
			));
		} else {
			//没有参数 则取cookie中的值
			$lang = $this->input->cookie('lang');
			if (!$lang) {
				$lang = 'zh';
			}
		}

		$from = $this->input->server('HTTP_REFERER');
		header("Location: {$from}");
		exie(0);
	}

	public function index() {
		$this->load->view('common_index');
	}

	public function header() {
		$this->set_layout('simple_layout');
		$this->load_css('common_header');
		$this->rend('common_header');
	}

	public function navigation() {
		$this->set_layout('simple_layout');
		$this->load_css('common_navigation');
		$this->load_js('common_navigation');
		$this->rend('common_navigation');
	}

}